//
//  Int+Additions.swift
//  MGExtensionsKit
//
//  Created by Max's mini on 2020/6/22.
//

import Foundation

public extension Int {
    var key: String {
        return "\(self)"
    }
    
    /// Int -> x.y  | x.yz (四舍五入, 保留places位小数)
    func countCondensation(places: Int = 1) -> String {
        if self < 10000 {
            return "\(self)"
        }
        let decimal = Double(self) / 10000
        let divisor = pow(10.0, Double(places))
        let number = (decimal * divisor).rounded() / divisor
        var numberString = "\(number)"
        if numberString.hasSuffix("0") {
            numberString = numberString.components(separatedBy: ".").first ?? numberString
        }
        return numberString
    }
    
    /// Int -> x.y 万
    func countDescription(wanSymbol: String = "万") -> String {
        if self < 10000 {
            return "\(self)"
        }
        let decimal = Double(self) / 10000
        let divisor = pow(10.0, Double(1))
        let number = (decimal * divisor).rounded() / divisor
        var numberString = "\(number)"
        if numberString.hasSuffix("0") {
            numberString = numberString.components(separatedBy: ".").first ?? numberString
        }
        return numberString + wanSymbol
    }
    
    /// Int -> KB \ MB \ GB
    func kbMbGb() -> String {
        let size = Double(self)
        if (size > pow(1024, 3)) {
            return String(format: "%.2f", size / pow(1024, 3)) + " GB"
        } else if (size > pow(1024, 2)) {
            return String(format: "%.2f", size / pow(1024, 2)) + " MB"
        } else {
            return String(format: "%.2f", size / pow(1024, 1)) + " KB"
        }
    }
    
    /// Int -> hh:mm:ss
    func hhmmss() -> String {
        let s = self % 60
        let m = self % 3600 / 60
        let h = self / 3600
        var text = ""
        if h > 0 {
            text += (h < 10 ? "0" : "") + "\(h)" + ":"
        }
        text += (m < 10 ? "0" : "") + "\(m)" + ":"
        text += (s < 10 ? "0" : "") + "\(s)"
        return text
    }
    
    var timeComponents: (day: Int, hour: Int, minute: Int, second: Int) {
        let day = Int(self) / (24 * 3600)
        let hour = Int(self) % (24 * 3600) / 3600
        let minute = Int(self) % (24 * 3600) % 3600 / 60
        let second = Int(self) % (24 * 3600) % 3600 % 60
        return (day, hour, minute, second)
    }
}
